package com.example.controller;

import com.example.common.constant.MessageConstant;
import com.example.common.exception.BaseException;
import com.example.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.UUID;

/**
 * 通用接口
 */

@RestController
@RequestMapping("/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Value("${file.upload-folder}")
    private String filePath;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(@RequestParam("file") MultipartFile file){
        log.info("文件上传：{}",file);
        // 检查文件是否为空
        if (file == null) {
            return Result.error("文件为空");
        }
        try {
            //获取文件后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
            if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
                throw new BaseException("请选择jpg,jpeg,gif,png格式的图片");
            }
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //利用UUID构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            File savePathFile = new File(filePath);
            if (!savePathFile.exists()) {
                //若不存在该目录，则创建目录
                savePathFile.mkdir();
            }

            File saveFile = new File(new File(filePath).getAbsolutePath()+"/"+objectName);
            file.transferTo(saveFile);

            //返回文件名称
            return Result.success(objectName);
        } catch (IOException e) {
            log.error("文件上传失败：",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

    /**
     * 获取图片接口
     * @param imagePath
     * @return
     * @throws IOException
     */
    @GetMapping("/image")
    @ApiOperation("获取图片接口")
    public Result<String> getImage(@RequestParam String imagePath) throws IOException {
        log.info("获取图片:{}",imagePath);// 检查文件是否存在
        // 指定本地图片的路径
        Path path = Paths.get(filePath + imagePath);
        //检查图片是否存在
        if (!Files.exists(path)) {
            log.error("文件不存在: {}", path);
            throw new BaseException("文件不存在");
        }
        byte[] imageBytes = Files.readAllBytes(path);
        // 转换为Base64格式
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        return Result.success(base64Image);
    }

}
